package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GetReferenceExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistTask(emf);
        persistEmployee(emf);
        emf.close();
    }
    private static void persistTask(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Task task = new Task("Task 1");
        em.getTransaction().begin();
        em.persist(task);
        em.getTransaction().commit();
        em.close();
    }
    private static void persistEmployee(EntityManagerFactory emf){
        Employee employee = new Employee();
        employee.setName("Joe");
        EntityManager em = emf.createEntityManager();
        Task task = em.getReference(Task.class,1);
        employee.setTask(task);
        em.getTransaction().begin();
        em.persist(employee);
        em.getTransaction().commit();
        List<Employee> employees = em.createQuery("select e from Employee e").getResultList();
        System.err.println(JSONObject.toJSONString(employees,true));
        em.close();
    }
}
